package com.lagace.spark.twitter;

import java.net.MalformedURLException;

import javax.swing.ImageIcon;

import org.jivesoftware.sparkimpl.plugin.alerts.SparkToaster;

import winterwell.jtwitter.Twitter.Status;

public class TwitterUtil {
	
	static final String SPACE = " ";
	static final String ANCHOR_BEGIN_OPEN_BRACKET = "<a style=\"color:#4bf\" href=\"";
	static final String ANCHOR_END = "</a>";
	static final String ANCHOR_BEGIN_CLOSE_BRACKET = "\">";
	
	public static String insertAnchors(final String messageText) {
		if(null == messageText) return "";
		if(messageText.indexOf("http") == -1) return messageText;
		String[] split = messageText.split(SPACE);
		StringBuffer sb = new StringBuffer();
		if(split.length > 0){
			for(int i=0;i<split.length;i++){
				if(split[i].startsWith("http")){
					
					sb.append(ANCHOR_BEGIN_OPEN_BRACKET+split[i].substring(0)+ANCHOR_BEGIN_CLOSE_BRACKET+ split[i].substring(0) + ANCHOR_END + SPACE);
				}else{
					sb.append(split[i] + SPACE);
				}
			}
		}
		return sb.toString();
	}
	
	public static void showToastFor(Status status) {
		try {
			ImageIcon icon = new ImageIcon(status.getUser().getProfileImageUrl().toURL());
			SparkToaster st = new SparkToaster();
			st.setTitle(status.getUser().getScreenName());
	        st.showToaster(icon, status.getText());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	
	public static boolean isNotBlank(String txt) {
		return null != txt && txt.trim().length() > 0;
	}
	
	public static String toTimelineFormat(long messageTimeMillis, long currentTimeMillis) {
		if( ((currentTimeMillis - messageTimeMillis) / 60 / 1000) < 1 )
			return "Less than 1 minute ago";
		if( ((currentTimeMillis - messageTimeMillis) / 60 / 1000) == 1 ) 
			return "1 minute ago";
		if( ((currentTimeMillis - messageTimeMillis) / 60 / 1000) < 60 ) 
			return ((currentTimeMillis - messageTimeMillis) / 60 / 1000) + " minutes ago";
		if( ((currentTimeMillis - messageTimeMillis) / 60 / 1000 / 60) == 1 ) 
			return "1 hour ago";
		if( ((currentTimeMillis - messageTimeMillis) / 60 / 1000 / 60) < 24 ) 
			return ((currentTimeMillis - messageTimeMillis) / 60 / 1000 / 60) + " hours ago";
		if( ((currentTimeMillis - messageTimeMillis) / 60 / 1000 / 60 / 24) == 1 ) 
			return "1 day ago";
		if( ((currentTimeMillis - messageTimeMillis) / 60 / 1000 / 60 / 24 ) < 7 ) 
			return ((currentTimeMillis - messageTimeMillis) / 60 / 1000 / 60 / 24) + " days ago";
		if( ((currentTimeMillis - messageTimeMillis) / 60 / 1000 / 60 / 24 / 7) == 1 )
			return "1 week ago";
		else
			return ((currentTimeMillis - messageTimeMillis) / 60 / 1000 / 60 / 24 / 7) + " weeks ago";
	}
}
